<script setup>
import { ref, onMounted } from 'vue'
import { useSetDefAddressService } from '@/api/requsets/index.js'

import { useUserStore, useAddressStore } from '@/stores/index.js'
import { useRouter } from 'vue-router'

// 用户信息仓库
const userStore = useUserStore()
// 用户地址信息仓库
const addressStore = useAddressStore()

//
const defAddressId = ref()

const router = useRouter()

onMounted(async () => {
  defAddressId.value = addressStore.defAddressId
  if (userStore.token && addressStore.userAddressList.length > 0) return
  await addressStore.getUserAddressData()
})

// 新增地址的回调
const onAdd = () => {
  router.push('/address/add')
}

// 点击编辑的回调
const onEdit = (item) => {
  console.log(item)
  router.push({
    path: '/address/update',
    query: {
      addressId: item.id
    }
  })
}

// 切换默认的回调
const setDef = async (item) => {
  await addressStore.setDefAddress({ addressId: item.id })
}
</script>

<template>
  <div id="address">
    <van-nav-bar title="收货地址" left-arrow @click-left="$router.go(-1)" />
    <div class="address-list">
      <van-address-list
        v-model="defAddressId"
        :list="addressStore.userAddressList"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
        @select="setDef"
      />
      <van-empty
        v-if="addressStore.userAddressList.length === 0"
        image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png"
        image-size="80"
        description="您的地址为空哦，快去新增吧"
      />
    </div>
  </div>
</template>

<style lang="less">
#address {
  position: relative;
  overflow: hidden;
  .address-list {
    min-height: 100vh;
    background-color: #f7f8fa;

    .van-address-item .van-radio__icon--checked .van-icon {
      background-color: red;
      border-color: red;
    }
    .van-tag--primary {
      background-color: red;
    }
    .van-button--primary {
      background-color: red;
      border-color: red;
    }
  }
}
</style>
